//
//  HYYOauthViewController.swift
//  Hyy9Weibo
//
//  Created by Air on 16/3/28.
//  Copyright © 2016年 hyy. All rights reserved.
//

import UIKit

import SVProgressHUD

class HYYOauthViewController: UIViewController {

    override func loadView() {
        //在这里设置控制器的View为webView的好处是后面需要添加约束，自己会和屏幕一样大
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        //设置导航栏
        setupNavigationBar()
        
        //使用webView来加载登陆界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString) //登陆界面url需要查看api文档
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        //弹出正在加载提示
        //showWithStatus不会自动关闭
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Gradient)
    }

    
    //设置导航栏
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HYYOauthViewController.autoFill))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HYYOauthViewController.close))
    }
    
    //MARK: - 点击方法
    @objc private func autoFill(){
        //js代码的字符串
        let jsCode = "document.getElementById('userId').value = '1070320@uc.cn';document.getElementById('passwd').value = 'hyy91119'"
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    //关闭控制器
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    //webView
    private lazy var webView:UIWebView = UIWebView()
}

//MARK: - 扩展HYYOauthViewController 实现 UIWebViewDelegate
extension HYYOauthViewController : UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
//        print("urlString : \(urlString)")
        //点击取消 http://hyy9.blogbus.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        //点击授权 http://hyy9.blogbus.com/?code=5b06174d91da7b5bc793af7ca2ac8bcb
        
        //当点击了取消或授权都会加载授权回调地址，所以判断如果是授权回调地址就表示点击了 取消 或 授权
        //不是授权回调地址，让他加载
        if !urlString.hasPrefix(redirect_uri){
            return true
        }else{
            //加载的授权回调地址，说明点击是 取消 或 授权
            //获取参数
            //query :get请求？后面的参数
            let query = request.URL?.query
            
            //判断query是否以code=开头
            let codeString = "code="
            if query!.hasPrefix(codeString){
                //点击的是授权
                //截取query的code
                let nsQuery = query! as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code : \(code)")
                
                //3.准备好闭包
                HYYUserAccountModel.sharedInstance.loadAccessToken(code, completion: { (error) in
                    //判断是否有错
                    if error != nil {
                        print("error : \(error)")
                        SVProgressHUD.showErrorWithStatus("获取AccessToken失败")
                        //延迟一秒再关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
                            self.close()
                        })
                        
                        return
                    }
                    //没有错误
                    //关闭控制器
                    print("没有错误关闭控制器")
                    SVProgressHUD.dismiss()
                    self.close()
                    
                    //切换控制器
//                    let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//                    appDelegate?.window?.rootViewController = HYYMainViewController()
//                    appDelegate?.swithRootViewController(HYYMainViewController())
                    AppDelegate.outSwitchRootViewController(HYYMainViewController())
                    
                })
            }else{
                //点击的是取消
                //关闭页面
                close()
            }
            return false
        }
        
    }
    
    /*
     MVVM
     MVC控制器管的事情太多了会导致控制器代码太多，逻辑太复杂，不方便代码维护
     VM专门来负责模型相关操作
     */
    
   }
